<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class ExternalBuy extends CI_Controller
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *        http://example.com/index.php/welcome
     *    - or -
     *        http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m', 'fun');
        $this->load->model('Externalbuy_m', 'm');
		$this->load->model('Product_m', 'product');
        $this->pageSize = $this->config->item('pagenum');
    }

    public function extBuyList()
    {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;
        $where = "";

        if ($this->input->get('status')) {
            $where .= " AND status = '" . $this->input->get('status') . "'";
            $this->tpl->assign("status", trim($this->input->get_post('status')));
        }
        //操作人员
        $createName = trim($this->input->get('createName'));
        if($createName){
            //$where.= " AND developer like '%".$createName."%'";
            $where.= " AND protector like '%".$createName."%'"; //维护者 为后来的开发者
            $this->tpl->assign('createName',$createName);
        }
        //受推荐人
        $recommender = trim($this->input->get("recommender"));
        if($recommender){
            $where .= " AND receivers like '%,".$recommender.",%' ";
            $this->tpl->assign('recommender',$recommender);
        }

		
		if($createName=="")
		{
			$where.=" and types = 0 ";
		}
        /**  权限放开
        if($_COOKIE["classid"] ==8)	//产品部人员 只能看到自己开发的产品
        {
            $userid = $_COOKIE['userid'];
            $where.=" AND createID = {$userid} ";
        }**/

        $ty = $this->input->get('ty');
        if($ty==1)$feil = "createTime";
        if($ty==2)$feil = "finishTime";
        $this->tpl->assign("ty", $ty);
        $starttime = trim($this->input->get('starttime'));
        if ($starttime) {
            $times = $starttime . " 00:00:00";
            $where .= " AND ({$feil} >= '" . $times . "')";
            $this->tpl->assign("starttime", $starttime);
        }

        $endtime = trim($this->input->get('endtime'));
        if ($endtime) {
            $times = $endtime . " 23:59:59";
            $where .= " AND ({$feil} <= '" . $times . "')";
            $this->tpl->assign("endtime", $endtime);
        }

        if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k `sku` LIKE  '%" . $r . "%' or p_parent_name LIKE '%" . $r . "%'";
                }
                $where .= ")";

            } else {
                $where .= " and  (sku LIKE  '%" . $other . "%'
					or p_parent_name LIKE '%" . $other . "%'
					or `p_en_goods_name` LIKE  '%" . $other . "%'
					) ";
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }
        $arr_reverse_developer = explode("|",trim($this->config->item('externalbuyemployee')));

        $this->tpl->assign('arr_employee',$arr_reverse_developer);

        //推荐接收者
        $receivers_config = trim($this->config->item('externalbuyreceivers'));
        $arr_receiver_config = explode("|",$receivers_config);
        $str_receiver = "";
        foreach($arr_receiver_config as $k=>$v){
            $str_receiver.= "'".trim($v)."'".",";
        }
        $str_receiver = trim($str_receiver,",");
        $receiverlist = $this->db->get_where('d_user'," type=1  AND name in ($str_receiver) ")->result_array();
        $this->tpl->assign("receiverlist", $receiverlist);
		 $this->tpl->assign("receiverlistinstructions",$this->config->item('externalbuyreceivers_instructions') );

        //显示确认上架，取消上架相关原因
        $users = $this->db->get_where('d_user'," type=1 ")->result_array();
        $arr_receiver = array();
        foreach($users as $kk=>$vv){
            $arr_receiver[$vv['id']] = $vv['name'];
        }
        $this->tpl->assign("arr_receiver", $arr_receiver);

        $where.= "AND del_flag = 0 ";
        $orderby = " order by id DESC";
        $list = $this->fun->getalllist('db_external_buy', $where, $nowpage, $if_csv, $this->pageSize, $orderby);
        $nums = $this->config->item("externalbuycounts");
        foreach ($list["list"] as $key => $rs) {
            $sql = "SELECT GROUP_CONCAT(subsku) as subsku FROM db_external_buygoods WHERE pid = {$rs['id']} and del_flag = 0 ";
            $result = $this->db->query($sql)->row_array();
            $list['list'][$key]['subsku'] = explode(",",$result['subsku']);

            $list['list'][$key]['en_goods_name'] = $rs['p_en_goods_name'];

            if ($_COOKIE["username"] == $rs["createName"]) {
                $list["list"][$key]["mod"] = 1;
            } else {
                $list["list"][$key]["mod"] = 0;
            }

            $receivers = trim($rs['receivers'],",");
            $receivers = explode(",",$receivers);
            //$list["list"][$key]["receivers"] = explode(",",$receivers); //所有有返回消息的接受者
            //返回相关信息
            $return_reason = explode(",",$rs['return_reason']);
            $arr_msg = array();
            foreach($receivers as $k=>$v){
                $arr_msg[$k]['userid'] = $v;
                $arr_msg[$k]['flag']=0;
                $arr_msg[$k]['address']=0;
                foreach($return_reason as $kk=>$vv){
                    $arr_reason = explode("-",$vv);

                    if($v==$arr_reason[0]){
                        $arr_msg[$k]['flag']=$arr_reason[1];
                        $str_con = $arr_reason[0]."-".$arr_reason[1]."-";
                        $arr_msg[$k]['address']=str_replace($str_con,"",$vv);
                        break;
                    }
                }
            }
            $list["list"][$key]["receivers"] = $arr_msg; //所有有返回消息的接受者

            $sql_goods = "SELECT SUM(sales1) as sales1,goods_name FROM db_goods WHERE goods_parent_sku = '{$rs['sku']}' ";
            $rs_goods  = $this->db->query($sql_goods)->row_array();
            if($rs_goods){
                $list["list"][$key]["sales1"] = $rs_goods['sales1'];
            }else{
                $list["list"][$key]["sales1"] = 0;
            }


            //获取商品图片
            $ProductImages = $this->m->getProductImages($rs["id"]);
            if($ProductImages)
            {
                $imgurl = dirname(__FILE__) . "/../..".$ProductImages[0]["thumb_url"];
                if(file_exists($imgurl))
                {
                    $list["list"][$key]["images"] = $ProductImages[0]["thumb_url"];
                }else{
                    $list["list"][$key]["images"] = "/fuman/images/s-l500.jpg";
                }
            }else{
                $list["list"][$key]["images"] = "/fuman/images/s-l500.jpg";
            }

            //判断是否可以转正开发
			if($rs['status'] == 99)
			{
				$ressku = $this->fun->getdatabasesdetail("db_goods"," AND goods_parent_sku = '{$rs['sku']}' ","GROUP_CONCAT(goods_id) as  id");
				$str_goods_id = $ressku["id"];
			if($str_goods_id){
				$sql = "SELECT sum(goods_number) as saleNum FROM db_order_sell A left join db_order_list B on A.`order_id` = B.order_id  where A.`goods_id` in($str_goods_id) AND B.order_status in (4,5) ";
				//$sql = "SELECT sum(sales2) as saleNum,goods_name FROM db_goods WHERE goods_parent_sku = '{$rs['sku']}' ";
				$rsdb  = $this->db->query($sql)->row_array();
				if(count($rsdb)&&$rsdb['saleNum']>=$nums){
					$list["list"][$key]["reverseflag"] = 1;
				}else{
					$list["list"][$key]["reverseflag"] = 0;
				}

				if(count($rsdb)&&$rsdb['saleNum']>=1){
					$list["list"][$key]["showreport"] = 1;
				}else{
					$list["list"][$key]["showreport"] = 0;
				}
			}else{
				$list["list"][$key]["showreport"] = 0;
			}
				$list["list"][$key]["p_parent_name"] = $rs_goods["goods_name"];
				$list["list"][$key]["p_en_goods_name"] = $rs_goods["en_name"];
			}

        }

        //开发者 与维护者
        $userlist = $this->db->get_where('d_user'," classid in (2,3,4,5,6,8)")->result_array();
        $this->tpl->assign("userlist", $userlist);

        $userlist = $this->fun->getdatabaseslist('db_external_buy'," AND protector is NOT NULL and del_flag = 0",'DISTINCT(protector)');
        foreach($userlist as $key=>$rs)
        {
            $yuanl[] = $rs['protector'];
            $this->tpl->assign("searchuserlist", $yuanl);
        }


        $attribute = $this->db->get('db_goods_type')->result_array();
        $this->tpl->assign("attribute", $attribute);

        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("goodslist", $list["list"]);
		$this->tpl->assign("userclassidst", $_COOKIE["classid"]);
        $this->tpl->display("externalbuy/externalbuylist.tpl");
    }

    public function addNewproduct()
    {
        $detail = $this->db->get_where('db_external_buy', " id='" . $this->input->get('id') . "'")->result_array();
        $this->tpl->assign("detail", $detail[0]);
        $arr_shop = array();
        if($detail){
            $category = $this->db->get_where('db_goods_category'," id >32")->result_array();
            $this->tpl->assign("category", $category);
            //日志信息
            $sql_rs = "SELECT * FROM db_externalbuy_log WHERE pid = {$detail[0]['id']} ORDER BY id DESC ";
            $logs  = $this->db->query($sql_rs)->result_array();
            $this->tpl->assign('logs',$logs);

            //店铺复选框
            $arr_shop = explode(",",$detail[0]['platId']);
            $this->tpl->assign('arr_shop',$arr_shop);
            //受推荐人信息
            if($detail[0]['receivers']){
                $receivers = trim($detail[0]['receivers'],",");
                $sql_receiver = "SELECT id,name FROM d_user WHERE id in ({$receivers}) ";
                $rs_receiver  = $this->db->query($sql_receiver)->result_array();
                $this->tpl->assign('receiverlist',$rs_receiver);
                //有消息反馈者
                if($detail[0]['return_receivers']){
                    $arr_return_receivers = explode(",",$detail[0]['return_receivers']);
                    $this->tpl->assign('return_receivers',$arr_return_receivers);
                }else{
                    $this->tpl->assign('return_receivers',array());
                }

            }

            $arr_subskus = $this->db->get_where('db_external_buygoods', " del_flag = 0 AND pid='" . $detail[0]['id'] . "'")->result_array();
            $this->tpl->assign("arr_subskus",$arr_subskus);
            $this->tpl->assign("updflag",1);
            $this->tpl->assign("buyId",$detail[0]['id']);
        }

        $sku = trim($this->input->get('sku'));
        if($sku){
            $detail["goods_sku"] = $sku;
            $this->tpl->assign("goods", $detail);
        }
        $platlist = $this->db->get_where('db_platform')->result_array();
        $this->tpl->assign("platlist", $platlist);

        $categorylist = $this->db->get_where('db_goods_category', 'sort_id=0 and id>15')->result_array();
        $this->tpl->assign("categorylist", $categorylist);
        $attribute = $this->db->get('db_goods_type')->result_array();
        //$userlist = $this->db->get_where('d_user', 'classid = 8')->result_array();
        $userlist = $this->db->get_where('d_user'," classid in (2,3,4,5,6,8)")->result_array();
        $this->tpl->assign("userlist", $userlist);



        $this->tpl->assign("salestatus", $this->status);
        $this->tpl->assign("attribute", $attribute);
        
        if($this->input->get('show')==1)
        {
            $this->tpl->display("externalbuy/addNewproductshow.tpl");
        }else{
            $this->tpl->display("externalbuy/addNewproduct.tpl");
        }
    }
    public function saveExtProduct(){
        //先查询是否有母商品
        $buyId = trim($this->input->post('buyId'));
        if(!$buyId){
            $sku = $this->input->post('sku');
            if ($sku == "") {
                $this->fun->phpalert(2, "SKU必须填写！", 'sku');
                exit;
            }
        }
        $this->db->trans_begin();

        $parentID = $this->m->saveExternalBuy($buyId);
        //再保存子商品信息
        $goods_id = $this->m->saveExternalBuygoods($parentID,$buyId);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }

        header("location:/externalBuy/extBuyList");
    }
    public function importExcel(){
        ini_set('max_execution_time','1800');
        if($_FILES['file_excel']){
            //excel导入
            require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
            $arr_excel_file = $_FILES['file_excel'];
            if(!empty($arr_excel_file)&&$arr_excel_file['error']==0) {
                $fileName = $arr_excel_file["name"];
                //$fileType = $arr_excel_file["type"];
                //$fileSize = $arr_excel_file["size"];
                $tmpFileName = $arr_excel_file["tmp_name"];
                //扩展名判断
                $fileExtName = explode(".", $fileName);
                $extName = $fileExtName[count($fileExtName)-1];
                if (!($extName == "xls" || $extName == "xlsx")) {
                    echo "上传的文件扩展名应该为.xls或.xlsx";
                    exit;
                }
                if ($extName == 'xlsx') {
                    $objReader = new PHPExcel_Reader_Excel2007();
                    $objExcel = $objReader->load($tmpFileName);
                } else if ($extName == 'xls') {
                    $objReader = new PHPExcel_Reader_Excel5();
                    $objExcel = $objReader->load($tmpFileName);
                }
                $sheet = $objExcel->getSheet(0);
                $rows = $sheet->getHighestRow(); //总行数
                $cols = $sheet->getHighestColumn(); //总列数 英文大写字母
                $arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                    'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
                    'AV','AW','AX','AY','AZ');
                $cols_length = array_search($cols, $arrCellName); //获取数组下标最大数
                $arr_externalbuy = array();
                //行
                for($row=2;$row<=$rows;$row++){
                    //列
                    for($column=0;$column<= $cols_length;$column++){
                        $cellValue = $arrCellName[$column].$row; //A2
                        $col_val = $sheet->getCell($cellValue)->getValue();
                        $col_val = trim($col_val);
                        //商品编号
                        if($column==0){
                            if(!$col_val){
                                break;
                            }
                            $arr_externalbuy[$row]['sku'] = $col_val;
                        }
                        //商品名称
                        if($column==1){
                            $arr_externalbuy[$row]['p_parent_name'] = $col_val;
                        }
                        //商品英文名称
                        if($column==2){
                            $arr_externalbuy[$row]['p_en_goods_name'] = $col_val;
                        }
                        //大分类
                        if($column==3){
                            $arr_externalbuy[$row]['p_bigclassid'] = $col_val;
                        }
                        //小分类
                        if($column==4){
                            $arr_externalbuy[$row]['p_secondclassid'] = $col_val;
                        }
                        //成本价
                        if($column==5){
                            $arr_externalbuy[$row]['p_costprice'] = $col_val;
                        }
                        //商品重量
                        if($column==6){
                            $arr_externalbuy[$row]['weight'] = $col_val;
                        }
                        //采购商家
                        if($column==7){
                            $arr_externalbuy[$row]['supplier'] = $col_val;
                        }
                        //采购连接
                        if($column==8){
                            $arr_externalbuy[$row]['address'] = $col_val;
                        }
                        //长
                        if($column==9){
                            $arr_externalbuy[$row]['length'] = $col_val;
                        }
                        //宽
                        if($column==10){
                            $arr_externalbuy[$row]['width'] = $col_val;
                        }
                        //高
                        if($column==11){
                            $arr_externalbuy[$row]['heigth'] = $col_val;
                        }
                        //开发人员
                        if($column==12){
                            $arr_externalbuy[$row]['developer'] = $col_val;
                        }
                        //维护人员
                        if($column==13){
                            $arr_externalbuy[$row]['protector'] = $col_val;
                        }
                        //材料信息
                        if($column==14){
                            $arr_externalbuy[$row]['fabricinfo'] = $col_val;
                        }
                        //备注信息
                        if($column==15){
                            $arr_externalbuy[$row]['memo'] = $col_val;
                        }
                        //尺码备注
                        if($column==16){
                            $arr_externalbuy[$row]['sizeinfo'] = $col_val;
                        }
                        //子sku信息
                        if($column==17){
                            $arr_externalbuy[$row]['subsku'] = $col_val;
                        }
                        //图片链接地址
                        if($column==18){
                            $arr_externalbuy[$row]['imagesUrl'] = $col_val;
                        }


                    }
                }
                //导入操作 返回导入数量
                $count = $this->m->importExcel($arr_externalbuy);
                if($count){
                    echo "导入成功";
                    echo "<br/>";
                    echo "总共导入:".$count." 条外采购商品";
                    exit;
                }else{
                    echo "导入失败";exit;
                }

            }

        }else{
           echo "未知错误";exit;
        }


    }
    public function updDeveloper(){
        $data = array();
        $id = trim($this->input->post("externalIds"),",");
        $protector = trim($this->input->post('protector'));

        //获取外采购商品开发人员对应的仓库
        $str_warehouse = $this->config->item('temporary_warehouse');
        $arr_warehouse = explode("\n",$str_warehouse);
        $arr_persons = array(); //维护人员
        $arr_positions = array();//具体仓库位置
        foreach($arr_warehouse as $k=>$v){
            $arr_value = explode("|",trim($v));
            $arr_persons[$k] = $arr_value[0];
            $arr_positions[$k]=$arr_value[1];
        }
        $positions = "";
        if(in_array($protector,$arr_persons)){
            $key = array_search($protector,$arr_persons);
            $positions = $arr_positions[$key]; //仓库位置
        }

        $sql = "SELECT * FROM db_external_buy WHERE id in ({$id})  ";
        $rs  = $this->db->query($sql)->result_array();
        $this->db->trans_begin();
        if($rs){
            foreach($rs as $key=>$value){
				/*
                $data['protector'] = $protector;
				$data['types'] = 1;
                $this->db->update('db_external_buy',$data," id=".$value['id']);
                $sql_sr = "SELECT * FROM db_goods_parent WHERE p_parent_sku = '{$value['sku']}' ";
                $sr  =  $this->db->query($sql_sr)->row_array();
                if($sr['p_buyer']==$value['developer']){

					


                    $this->db->update('db_goods_parent',array('p_checkman'=>$data['protector'],'p_buyer'=>$data['protector'])," p_parent_sku = '".$value['sku']."'");
                }else{
                    $this->db->update('db_goods_parent',array('p_checkman'=>$data['protector'])," p_parent_sku = '".$value['sku']."'");
                }
                $sql_goods = "SELECT * FROM db_goods WHERE goods_parent_sku = '".$value['sku']."'";
                $result = $this->db->query($sql_goods)->result_array();
                if(count($result)>0){
                    foreach($result as $k=>$v){
                        if($positions){
                            $sql_stock = "SELECT * FROM db_goods_stock WHERE storage_id = 1 AND goods_id = '{$v['goods_id']}' ";
                            $rs_stock  = $this->db->query($sql_stock)->row_array();
                            if(count($rs_stock)>0){
                                if(!$rs_stock['positions']){
                                    $this->db->update('db_goods_stock',array("positions"=>$positions)," storage_id = 1 AND goods_id = '".$v['goods_id']."'");
                                }else{
                                    if(in_array($rs_stock['positions'],$arr_positions)){
                                        $this->db->update('db_goods_stock',array("positions"=>$positions)," storage_id = 1 AND goods_id = '".$v['goods_id']."'");
                                    }else{
                                        //不做更新，可能仓位已经设定
                                    }
                                }

                             }
                        }
                        $rval = "";
                        $flag = 0;
                        if($v['g_buyer']==$value['developer']){
                            $rval.= "原采购人员：".$v['g_buyer']." 更新为: ".$data['protector'];
                            $flag = 1;
                        }
						$rval.=" 原维护人员：".$v["g_checkman"]." 更新为：".$data["protector"]."";
						$this->fun->goods_update_log($v['goods_id'],$rval,1);	//更新商品信息
                        if($flag==1){
                            $this->db->update('db_goods',array('g_buyer'=>$data['protector'],'g_checkman'=>$data['protector'])," goods_id = ".$v['goods_id']);
                        }else{
                            $this->db->update('db_goods',array('g_checkman'=>$data['protector'])," goods_id = ".$v['goods_id']);
                        }

                    }
                }
				*/
				$data['protector'] = $protector;
				$data['types'] = 1;
                $this->db->update('db_external_buy',$data," id=".$value['id']);
				if($protector=='姜鸿辉')
				{
					$p_buyer ='7777';
				}
				if($protector=='曾月')
				{
					$p_buyer ='9999';
				}
				$this->db->update('db_goods_parent',array("p_buyer"=>$p_buyer,"p_checkman"=>$p_buyer,"memo"=>"开发人员{$value['protector']}离职，转入{$data['protector']}维护列表")," p_parent_sku='".$value['sku']."'");
                $msg = "维护者由：{$value['protector']},更改为：{$data['protector']}";
                $arr_logs['createtime'] = date("Y-m-d H:i:s");
                $arr_logs['pid'] = $value['id'];
                $arr_logs['goods_code'] = $value['sku'];
                $arr_logs['details'] = $msg;
                $arr_logs['username'] = $_COOKIE['username'];
                $arr_logs['userid'] = $_COOKIE['userid'];
                $this->db->insert('db_externalbuy_log', $arr_logs);

            }

        }
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
        //header("location:/externalBuy/extBuyList?other={$rs['sku']}");
        header("location:/externalBuy/extBuyList");
    }
	
	/********商品维护***************/
    public function Maintenance()
	{
		//高菲菲：假发、鞋子
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;
		
		$power = $_COOKIE['power'];
		if($power)
		{
			$power = explode(",",$power);
		}
		
		if(in_array(311,$power))	//修改状态权限
		{
			 $where = " AND p_buyer=11111";
		}else{
			 if($_COOKIE["userid"] == 297){
				$where = " AND p_buyer=7777";
			 }
			 if($_COOKIE["userid"] == 78){
				//$where = " AND p_buyer=6666";
				$where = " AND (p_buyer=9999 or  p_buyer=6666 or  p_buyer=7777 or  p_buyer=8888) ";
			 }
			 if($_COOKIE["userid"] == 184){
				$where = " AND p_buyer=8888";
			 }
			 if($_COOKIE["userid"] == 407){
				$where = " AND p_buyer=9999";
			 }
		}
		if($_COOKIE["department"]==1)
		{
			$where = " AND (p_buyer=11111 or  p_buyer=9999 or  p_buyer=6666 or  p_buyer=7777 or  p_buyer=8888) ";
		}
		$other = trim($this->input->get('sku'));
        if($other){
		    $where.= " AND (p_parent_sku='".$other."' or p_parent_name like '%".$other."%')";
			$this->tpl->assign("other", $other);
        }
		$status = trim($this->input->get('status'));
        if($status){
			if($status==1)
			{
				$where.= " AND memo like  '%建议下架%'";
			}else{
				$where.= " AND memo like  '%建议销售%'";
			}
			$this->tpl->assign("status", $status);
        }
		$orderby = " order by p_parent_id DESC";
        $list = $this->fun->getalllist('db_goods_parent', $where, $nowpage, $if_csv, $this->pageSize, $orderby);
		foreach($list["list"] as $key=>$rsdb)
		{
			$goods = $this->fun->getdatabasesdetail("db_goods"," AND goods_parentID  = '".$rsdb["p_parent_id"]."'","GROUP_CONCAT(goods_id) as goods_id");
			$starttime = date("Y-m-d",$rsdb["p_intime"]);
			$endtime = date("Y-m-d");
			$allday1= $this->fun->get_goods_sale($goods["goods_id"],$starttime,$endtime);
			$allday2= $this->fun->get_goods_fba_sale($goods["goods_id"],$starttime,$endtime);
			$list["list"][$key]["allday1"] = $allday1;
			$list["list"][$key]["allday2"] = $allday2;
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("goodslist", $list["list"]);
		$this->tpl->assign("userclassidst", $_COOKIE["classid"]);
        $this->tpl->display("externalbuy/Maintenance.tpl");
	}

    /********商品状态列表***************/
    public function productStatusList()
    {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;
        $where = "";
        $other = trim($this->input->get('sku'));
       //print_r($other);exit;
        if($other){
            $where.= " AND p_parent_sku='".$other."'";
            $this->tpl->assign("other", $other);
        }
            $where.= " AND type = 1 ";
         $orderby = " order by p_parent_id DESC";

        $list = $this->fun->getalllist('db_goods_status', $where, $nowpage, $if_csv, $this->pageSize, $orderby);
        foreach($list["list"] as $key=>$rsdb)
        {
            $goods = $this->fun->getdatabasesdetail("db_goods_parent"," AND p_parent_id  = '".$rsdb["p_parent_id"]."'","*");
            $list["list"][$key]["p_parent_name"] = $goods['p_parent_name'];
        }

        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("goodslist", $list["list"]);
        $this->tpl->display("externalbuy/productstatuslist.tpl");
    }
    public function ajaxbutton()
    {
        $op = trim($_REQUEST["op"]);
        /******保存流程状态信息************/
        if($op =='changestatus')
        {
            $status = trim($this->input->post('status'));
            $id = trim($this->input->post('id'));
            //status  9999 已完成 1 样品采购 2 确认开发(待出图） 3 出图（已出图状态）  4 作废(终止开发) 5.删除
            if($status == 2){
                //更新长宽高相关信息
                $data = array();
                $data['status'] = 2; //更新状态 待出图
                $this->db->update('db_external_buy',$data,"id=".$id);

                //消息提示美工出图   美工部主管 沈宝怡
                $sql = "SELECT * FROM db_external_buy WHERE id = {$id} ";
                $result = $this->db->query($sql)->row_array();

                $msg = "状态由：样品采购，更改为：待出图";
                $arr_logs['createtime'] = date("Y-m-d H:i:s");
                $arr_logs['pid'] = $id;
                $arr_logs['goods_code'] = $result['sku'];
                $arr_logs['details'] = $msg;
                $arr_logs['username'] = $_COOKIE['username'];
                $arr_logs['userid'] = $_COOKIE['userid'];
                $this->db->insert('db_externalbuy_log', $arr_logs);


                $randid = $this->message->getMessageNums();	//获取当前存储的条数
                $packingman[] = $_COOKIE['username'];
                $packingman[] = "沈宝怡"; //目前只发美工部，该人员
                foreach($packingman as $rs)
                {
                    $postMessageData["message_type"] = $this->message->getMessageType(0);	//消息提醒
                    $message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."外采购商品【{$result['sku']}】已确认开发";
                    $message.="，待出图状态！请相关人员出图！";
                    $postMessageData["message"] = $message;
                    $postMessageData["message_toName"] = $rs;
                    $postMessageData["isread"] =  $randid;
                    $postMessageData["url"] = '/externalBuy/extBuyList?other='.$result['sku'];
                    $this->fun->saveMessage($postMessageData);
                }

            }
            if($status == 3){ //已出图
                $this->db->update('db_external_buy',array('status'=>3),"id=".$id);

                //消息提示  提示开发人员 美工已经出图
                $sql = "SELECT * FROM db_external_buy WHERE id = {$id} ";
                $result = $this->db->query($sql)->row_array();

                $msg = "状态由：待出图，更改为：已出图";
                $arr_logs['createtime'] = date("Y-m-d H:i:s");
                $arr_logs['pid'] = $id;
                $arr_logs['goods_code'] = $result['sku'];
                $arr_logs['details'] = $msg;
                $arr_logs['username'] = $_COOKIE['username'];
                $arr_logs['userid'] = $_COOKIE['userid'];
                $this->db->insert('db_externalbuy_log', $arr_logs);

                $randid = $this->message->getMessageNums();	//获取当前存储的条数
                $packingman[] = $result['developer'];
                foreach($packingman as $rs)
                {
                    $postMessageData["message_type"] = $this->message->getMessageType(0);	//消息提醒
                    $message = "美工".$_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."外采购商品【{$result['sku']}】已出图";
                    $message.="，请相关人员进行后续操纵！";
                    $postMessageData["message"] = $message;
                    $postMessageData["message_toName"] = $rs;
                    $postMessageData["isread"] =  $randid;
                    $postMessageData["url"] = '/externalBuy/extBuyList?other='.$result['sku'];
                    $this->fun->saveMessage($postMessageData);
                }

            }
            if($status == 4){//终止开发

                $sql_buy  = "SELECT * FROM db_external_buy WHERE id = '{$id}' ";
                $rs_buy   = $this->db->query($sql_buy)->row_array();
				
				$sql = "SELECT * FROM db_external_buy WHERE id = {$id} ";
                $result = $this->db->query($sql)->row_array();
			
                $msg = "状态修改为：终止开发";
                $arr_logs['createtime'] = date("Y-m-d H:i:s");
                $arr_logs['pid'] = $id;
                $arr_logs['goods_code'] = $result['sku'];
                $arr_logs['details'] = $msg;
                $arr_logs['username'] = $_COOKIE['username'];
                $arr_logs['userid'] = $_COOKIE['userid'];
                $this->db->insert('db_externalbuy_log', $arr_logs);


                if(isset($result['status'])&&$result['status']==99){ //已经完成的终止开发
					$this->db->update('db_external_buy',array('status'=>4),"id=".$id);
                    $sql_goods = "SELECT * FROM db_goods WHERE goods_parent_sku = '{$result['sku']}' ";
                    $rs_goods  = $this->db->query($sql_goods)->row_array();
                    $this->load->model('Product_m', 'mp');
                    //$this->mp->getdelproduct($rs_goods['goods_id']);
				     $statusPid =  $rs_goods["goods_parentID"];
					if($statusPid){
						$this->mp->savestatus($statusPid, 1, 6);
					}
                    echo json_encode(array(99));exit;
                }

                $this->db->update('db_external_buy',array('status'=>4),"id=".$id);
                //消息提示 美工终止开发   美工部主管 沈宝怡
                

//                $msg = "状态修改为：终止开发";
//                $arr_logs['createtime'] = date("Y-m-d H:i:s");
//                $arr_logs['pid'] = $id;
//                $arr_logs['goods_code'] = $result['sku'];
//                $arr_logs['details'] = $msg;
//                $arr_logs['username'] = $_COOKIE['username'];
//                $arr_logs['userid'] = $_COOKIE['userid'];
//                $this->db->insert('db_externalbuy_log', $arr_logs);

                $randid = $this->message->getMessageNums();	//获取当前存储的条数
                $packingman[] = $_COOKIE['username'];
                $packingman[] = "沈宝怡"; //目前只发美工部，该人员
                foreach($packingman as $rs)
                {
                    $postMessageData["message_type"] = $this->message->getMessageType(0);	//消息提醒
                    $message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."外采购商品【{$result['sku']}】已终止开发";
                    $message.=",相关人员请知悉！";
                    $postMessageData["message"] = $message;
                    $postMessageData["message_toName"] = $rs;
                    $postMessageData["isread"] =  $randid;
                    $postMessageData["url"] = '/externalBuy/extBuyList?other='.$result['sku'];
                    $this->fun->saveMessage($postMessageData);
                }
            }
            if($status == 5){ //删除
                $this->db->update('db_external_buy',array('del_flag'=>1),"id=".$id);
                //$this->db->delete('db_product_buy',array('id' => $id));
            }
            if($status == 99){ //已完成

                $id = trim($this->input->post('buyId'));
                //已完成 对相关数据表进行操作 db_goods db_goods_parent db_goods_stock db_goods_purchasing
                //db_goods_images db_external_buy db_external_buygoods db_externalbuy_log  db_goods_log
                $this->db->trans_begin();

                $sql = "SELECT * FROM db_external_buy WHERE id = {$id} ";
                $result = $this->db->query($sql)->row_array();
                $msg = "状态由：已出图，更改为：已完成";
                $arr_logs['createtime'] = date("Y-m-d H:i:s");
                $arr_logs['pid'] = $id;
                $arr_logs['goods_code'] = $result['sku'];
                $arr_logs['details'] = $msg;
                $arr_logs['username'] = $_COOKIE['username'];
                $arr_logs['userid'] = $_COOKIE['userid'];
                $this->db->insert('db_externalbuy_log', $arr_logs);

                //更新相关数据 长宽高重量等信息
                $data = array();
                $data['weight'] = trim($this->input->post('weight'));
                if(trim($this->input->post('length'))){
                    $data['length'] = trim($this->input->post('length'));
                }
                if(trim($this->input->post('width'))){
                    $data['width']  = trim($this->input->post('width'));
                }
                if(trim($this->input->post('heigth'))){
                    $data['heigth'] = trim($this->input->post('heigth'));
                }
                $data['status'] = 99;
                $data['finishTime'] = date("Y-m-d H:i:s");
                $this->db->update('db_external_buy',$data,"id=".$id);

                $parentID = $this->m->saveparent($id);

                if ($this->db->trans_status() === FALSE) {
                    $this->db->trans_rollback();
                } else {
                    $this->db->trans_commit();
                }
                $masterSku = trim($this->input->post('skuId'));
                header("location:/externalBuy/extBuyList?other={$masterSku}");
            }
            return true;
        }
        //添加链接
        if($op == "doFinish"){
            $external_id = trim($this->input->post("external_id"));
            $linkUrl = trim($this->input->post("linkUrl"));
            $this->db->update("db_external_buy",array("linkUrl"=>$linkUrl)," id = '".$external_id."'");
            echo 200;exit;
        }
        if($op=="productStatusList"){
            $nowpage = $_REQUEST["pageid"];
            if ($nowpage == "")
                $nowpage = 1;
            $where = "";
            $other = trim($this->input->get('sku'));
            //print_r($other);exit;
            if($other){
                $where.= " AND (p_parent_sku='".$other."' or reason='".$other."')";
                $this->tpl->assign("other", $other);
            }

            $type = trim($this->input->get('type'));
            if($type){
                $where.= " AND type = '{$type}' ";
                $this->tpl->assign("type", $type);
            }

            $orderby = " order by p_parent_id DESC";

            $list = $this->fun->getalllist('db_goods_status', $where, $nowpage, $if_csv, $this->pageSize, $orderby);
            foreach($list["list"] as $key=>$rsdb)
            {
                $goods = $this->fun->getdatabasesdetail("db_goods_parent"," AND p_parent_id  = '".$rsdb["p_parent_id"]."'","*");
                $list["list"][$key]["p_parent_name"] = $goods['p_parent_name'];
            }

            $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
            $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
            $this->tpl->assign("total", $list["total"]);
            $this->tpl->assign("pageList", $pageList);
            $this->tpl->assign("goodslist", $list["list"]);
            $this->tpl->display("externalbuy/productstatuslist.tpl");
        }
        if($op=="doRecommendGoods"){
            $str_ids = trim($this->input->post("ids"),","); //商品编号id
            //$str_receivers = trim($this->input->post("receiver"),","); //用户id
            $receivers = trim($this->input->post("receiver"),","); //用户id
            $arr_receivers = explode(",",$receivers);
            $arr_ids = explode(",",$str_ids);
            foreach($arr_ids as $k=>$v){
                $str_receivers = "";
                $sql = "SELECT * FROM db_external_buy WHERE del_flag = 0 AND status =99 AND  id= {$v} ";
                $rs  = $this->db->query($sql)->row_array();
                if(count($rs)>0){
                    if($rs['receivers']){
                        $flag = 0;
                        $receiver = trim($rs['receivers'],",");
                        $arr_receiver = explode(",",$receiver); //数据库中已存在用户
                        //新推荐用户 要过滤重复用户
                        $arr_new = array();
                        foreach($arr_receivers as $key=>$value){
                            if(in_array($value,$arr_receiver)){
                                continue;
                            }else{
                                $arr_new[] = $value;
                            }
                        }
                        if(count($arr_new)>0){
                            $str_receivers = $rs['receivers'].implode(",",$arr_new).",";
                            $flag = 1;
                        }
                    }else{
                        $str_receivers = ",".$receivers.",";
                        $flag = 1;
                    }
                    if($flag ==1){
                        $this->db->update('db_external_buy',array('receivers'=>$str_receivers)," del_flag = 0 AND id = {$v} ");
                    }
                }else{
                    continue;
                }
            }
            echo 200;exit; //推荐成功
            //$this->db->update('db_external_buy',array('receivers'=>$str_receivers)," del_flag = 0 AND id in ({$str_ids}) ");
            /**
            if($this->db->affected_rows()){
                echo 200;exit;
            }else{
                echo 0;exit;
            }**/
        }
        if($op=="delsubsku"){
            $id = trim($this->input->post('id'));
            $this->db->update("db_external_buygoods",array('del_flag'=>1),"id=".$id);
            echo 200;exit;
        }
		if($op =='showreport')
		{
			//报表
			$sku = trim($this->input->post('sku'));
			$type = trim($this->input->post('type'));	//1 正向开发 0其他
			$this->load->model('Datareport_m','datareport');
			$where=" AND ( goods_parent_sku like '%".$sku."%')";
			$ress = $this->datareport->saleplatform_m($where,'saleNum',1,$type);
			
			if($ress["total"]==0)
			{
				echo 201;
				die;
			}else{

				 //推荐接收者
				$receivers_config = trim($this->config->item('externalbuyreceivers'));
				$arr_receiver_config = explode("|",$receivers_config);
				$str_receiver = "";
				foreach($arr_receiver_config as $k=>$v){
					$str_receiver.= "'".trim($v)."'".",";
				}
				
				$str_receiver = trim($str_receiver,",");
				$receiverlist = $this->db->get_where('d_user'," type=1  AND name in ($str_receiver) ")->result_array();
				$arr_receiver = array();
				foreach($receiverlist as $kk=>$vv){
					$arr_receiver[$vv['id']] = $vv['name'];
				}
				if($type==1)
				{
					$tmall='<th class="head0">淘宝</th><th class="head0">Tmall</th><th class="head0">Yahoo</th>';
				}

				$tables = ' <table cellpadding="0"  id="table2" cellspacing="0" border="0" class="stdtable"> <thead><tr><th class="head0">商品编号</th>
         <th class="head0">总销售</th><th class="head1">AMZ一组 </th><th class="head1">AMZ二组</th>
          <th class="head1">AMZ三组</th><th class="head1">AMZ四组</th><th class="head1">AMZ五组</th><th class="head1">AMZ备用 </th><th class="head1">德国 </th><th class="head1">日本 </th><th class="head0">Ebay</th><th class="head0">Wish</th>
          <th class="head0">速卖通</th><th class="head0">网站</th> <th class="head0">Shopee</th>'.$tmall.'<th class="head0">推荐</th></tr> </thead>';
				  $rs = $ress["list"][0];
				
			
				if($rs["noplatform"] ==0)
				{
					$tables.=" <tr> <td><a href=\"/product/productlist?other={$rs[goods_parent_sku]}\" target=\"_blank\">{$rs[goods_parent_sku]}</a></td>";
					$tables.=" <td>{$rs[allsale]}</td>";
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Amazon'){$tables.=$res['str_amazon1'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Amazon'){$tables.=$res['str_amazon2'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Amazon'){$tables.=$res['str_amazon3'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Amazon'){$tables.=$res['str_amazon4'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Amazon'){$tables.=$res['str_amazon5'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Amazon'){$tables.=$res['str_usaa'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Amazon'){$tables.=$res['germany'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Amazon'){$tables.=$res['japan'];}else{}}
					$tables.='</td>';
		
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='ebay'){$tables.=$res['goods_number'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Wish'){$tables.=$res['goods_number'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='aliexpress'){$tables.=$res['goods_number'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Magento'){$tables.=$res['goods_number'];}else{}}
					$tables.='</td>';
					$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Shopee'){$tables.=$res['goods_number'];}else{}}
					$tables.='</td>';
					if($type==1)
					{
						$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='淘宝'){$tables.=$res['goods_number'];}else{}}
						$tables.='</td>';
						$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Tmall'){$tables.=$res['goods_number'];}else{}}
						$tables.='</td>';
						$tables.=" <td>";foreach($rs["platform"] as $key=>$res){if($res['name']=='Yahoo'){$tables.=$res['goods_number'];}else{}}
						$tables.='</td>';
					
					}

					$tables.=" <td>";
					$tablesrests = "";
					$buySKU = $this->fun->getdatabasesdetail('db_external_buy'," AND sku = '".$rs['goods_parent_sku']."'",'receivers');
					if($rs['receivers']){
						foreach($rs['receivers'] as $key=>$res)
						{
							if($res['flag'] ==1)
							{
								$tablesrests.="<a href=\"{$res[address]}\" style=\"color:red;\" target=\"_blank\">".$arr_receiver[$res['userid']]."&nbsp;</a>";
							}elseif($res['flag'] ==2)
							{
								$tablesrests.=" <a href=\"javascript:void(0);\"><s>".$arr_receiver[$res['userid']]."</s><span id=\"tip_info\">取消原因：{$res[address]}</span>&nbsp;</a>";
							}else{
								$tablesrests.=$arr_receiver[$res["userid"]]."&nbsp;&nbsp;";
							}
						}
					}
					$tables.="$tablesrests</td>";
					$tables.="</tr>";
				}
				$tables.=" </tbody></table>";
				echo $tables;
				die;
			}
			
			
		}
		if($op =='changMaintenancestatus')
		{
			$goods_parentID = $this->input->post('parid');
			$goods_id = substr($goods_parentID,0,-1);
			$goods_t = $this->input->post('t');
			if($goods_id && $goods_t==3){ //请求下架
				$this->db->update('db_goods_parent',array("p_buyer"=>11111,"p_checkman"=>11111)," p_parent_id in ($goods_id)");
                //请求下架日志信息
                $reason = $this->input->post("reason");
                $descr  = trim($this->input->post("descr"));
                $sql = "SELECT * FROM db_goods_parent WHERE p_parent_id in ($goods_id) ";
                $rs  = $this->db->query($sql)->result_array();
                foreach($rs as $k=>$v){
                    $imgdata = "";
                    $imgdata["p_parent_id"] = $v['p_parent_id'];
                    $imgdata["p_parent_sku"] = $v['p_parent_sku'];
                    $imgdata["type"] = 1; //请求下架
                    $imgdata["reason"] = $reason;
                    if($descr){
                        $imgdata["descr"] = $descr;
                    }
                    $imgdata["createUser"] = $_COOKIE['username'];
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["addTime"] = date("Y-m-d H:i:s");
                    $this->db->insert('db_goods_status', $imgdata);
                }
			}

			if($goods_id && $goods_t==1){
				//修改商品状态为下架
				//$this->status = array("1" => '新品', "2" => '正常销售', "3" => '重点产品', "4" => '停产', "5" => '清仓', "6" => '暂停销售', "7" => '下架');
				$this->status =$this->fun->get_sys_goods_status();
				$goods_id = explode(",",$goods_id);
				foreach($goods_id as $statusPid)
				{
					$this->product->savestatus($statusPid, 1,6,0);
					$rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_parentID ='".intval($statusPid)."' AND g_buyer !=''","g_buyer,g_checkman");
					$g_checkman = $rsdb["g_checkman"]?$rsdb['g_checkman']:'刘艺';
					$g_buyer = $rsdb["g_buyer"]?$rsdb['g_buyer']:'刘艺';
					$this->db->update('db_goods_parent',array("p_buyer"=>$g_buyer,"p_checkman"=>$g_checkman,"memo"=>'')," p_parent_id =".intval($statusPid));
				}
			}
			echo 200;
			die;
		}
		if($op =='saveMaintenanceSKU')
		{
			$goods_parentID = $this->input->post('parid');
			$goods_id = substr($goods_parentID,0,-1);
			if($goods_id)
			{
				$goods_id = explode(",",$goods_id);
				foreach($goods_id as $goodsparentID)
				{
					$this->m->saveMaintenanceSKU($goodsparentID);
					$g_checkman = $_COOKIE["username"];
					$g_buyer = $_COOKIE["username"];
					$this->db->update('db_goods_parent',array("p_buyer"=>$g_buyer,"p_checkman"=>$g_checkman,"memo"=>'')," p_parent_id =".intval($goodsparentID));
				}
			}
			echo 200;
			die;
		}
        //显示图片信息
        if ($op == 'showImages') {
            $result = $this->m->getProductImages($this->input->post('id'),$this->input->post('type'));
            echo json_encode($result);
            die;
        }

		if($op =='getexternalprotector')
		{
			$userlist = $this->fun->getdatabaseslist('db_external_buy'," AND protector is NOT NULL and del_flag = 0 AND protector !='刘艺' AND protector !='张仕鹏'",'DISTINCT(protector)');
			foreach($userlist as $key=>$rs)
			{
				$yuanl[] = $rs['protector'];
			}
			echo json_encode($yuanl);
            die;
		}
        /******保存JQ传回的Images信息************/
        if($op =='saveProductImages')
        {
            $id = $this->m->saveProductImages();
            $sql = "SELECT * FROM db_external_buy WHERE id = {$id} ";
            $rs  = $this->db->query($sql)->row_array();
            $this->fun->phpalert(4, "", '', "/externalBuy/extBuyList?other={$rs['sku']}");
        }
        if ($op == "delone") {
            if ($this->input->post('st') == 'externalbuy') {
                $del_flag = trim($this->input->post('delflag')); //删除该商品所有图片
                if($del_flag==1){
                    $uid = $this->input->post('id');
                    $type = $this->input->post('type');
                    if(!$type){
                        $type=0;
                    }
                    $rs  = $this->db->select()->from('db_externalbuy_images')->where('uid=' .$uid." AND type=".$type)->get()->result_array();
                    foreach($rs as $k=>$v){
                        $this->fun->delattfile($v["images_url"]);
                        $this->fun->delattfile($v["thumb_url"]);
                        $this->db->delete('db_externalbuy_images', 'id=' . $v['id']);
                    }
                    $res = array("txt" => 200, "url" => '/externalBuy/extBuyList?id=' . $uid);
                    echo json_encode($res);
                    die;

                }else{
                    //删除图片
                    $res = $this->db->select()->from('db_externalbuy_images')->where('id=' . $this->input->post('id'))->get()->result_array();
                    $this->fun->delattfile($res[0]["images_url"]);
                    $this->fun->delattfile($res[0]["thumb_url"]);
                    $this->db->delete('db_externalbuy_images', 'id=' . $res[0]["id"]);
                    //$this->db->delete('db_externalbuy_images', 'id=' . $this->input->post('id'));
                    $res = array("txt" => 200, "url" => '/externalBuy/extBuyList?id=' . $res[0]["uid"]);
                    echo json_encode($res);
                    die;

                }
            }
        }
        //获取外采购商品销售数量
        if($op=="getGoodsSalesCount"){
            $sku = trim($this->input->post("sku"));
            $nums = $this->config->item("externalbuycounts");
            $sql = "SELECT sum(saleNum) as saleNum FROM db_goods WHERE goods_parent_sku = '{$sku}' ";
            $rs  = $this->db->query($sql)->row_array();
            if(count($rs)&&$rs['saleNum']>=$nums){
                $arr = array("code"=>1,"saleNum"=>$rs['saleNum'],"nums"=>$nums);
            }else{
                 if(!$rs['saleNum']){
                     $rs['saleNum'] = 0;
                 }
                $arr = array("code"=>0,"saleNum"=>$rs['saleNum'],"nums"=>$nums);
            }
            echo json_encode($arr);exit;
        }
        //已完成 状态 更改开发者，维护者
        if($op == "updDeveloper"){
            $data = array();
            $id = trim($this->input->post("externalIds"),",");
            $protector = trim($this->input->post('protector'));
            $sql = "SELECT * FROM db_external_buy WHERE id in ({$id})  ";
            $rs  = $this->db->query($sql)->result_array();
            $this->db->trans_begin();
            if($rs){
                foreach($rs as $key=>$value){
                    $sql_buy = "SELECT * FROM db_external_buy WHERE id = '{$value['id']}' ";
                    $rs_buy  = $this->db->query($sql_buy)->row_array();

                    $data['protector'] = $protector;
					$data['types'] = 1;
                    $this->db->update('db_external_buy',$data," id=".$value['id']);

                    $this->db->update('db_goods_parent',array('p_checkman'=>$data['protector'])," p_parent_sku = '".$rs_buy['sku']."'");
                    $sql_goods = "SELECT * FROM db_goods WHERE goods_parent_sku = '".$rs_buy['sku']."'";
                    $result = $this->db->query($sql_goods)->result_array();
                    if(count($result)>0){
                        foreach($result as $k=>$v){
                            $this->db->update('db_goods',array('g_checkman'=>$data['protector'])," goods_id = ".$v['goods_id']);
                        }
                    }
                    $msg = "维护者由：{$value['protector']},更改为：{$data['protector']}";
                    $arr_logs['createtime'] = date("Y-m-d H:i:s");
                    $arr_logs['pid'] = $value['id'];
                    $arr_logs['goods_code'] = $rs_buy['sku'];
                    $arr_logs['details'] = $msg;
                    $arr_logs['username'] = $_COOKIE['username'];
                    $arr_logs['userid'] = $_COOKIE['userid'];
                    $this->db->insert('db_externalbuy_log', $arr_logs);

                }

            }
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
            } else {
                $this->db->trans_commit();
            }
            //header("location:/externalBuy/extBuyList?other={$rs['sku']}");
          //  header("location:/externalBuy/extBuyList");

        }


    }
}
